import { constantRouterMap } from "@/router/constant";
import GetRoutes from "@/router/map";
import { _import } from "@/router/_import";
import { getUserPermission } from "@/apis/user.js";
import { Session } from "@/utils/storage";

const permission = {
  namespaced: true,
  state: {
    cachRouter: [],
    routers: constantRouterMap,
    asyncRouter: [],
    addRouters: [],
    currentRouter: [],
    currentRouterIndex: Session.get("TOP_NAV_ACTIVE_KEY") || 0,
    sidebarActiveIndex: Session.get("MENU_ACTIVE_KEY") || "0",
  },
  mutations: {
    SET_ROUTERS: async (state, routers) => {
      state.asyncRouter = Conf.HAS_TOP_NAV ? routers : [];
      console.log(
        state.currentRouterIndex,
        routers[state.currentRouterIndex],
        "state.currentRouterIndex"
      );
      state.currentRouter = Conf.HAS_TOP_NAV
        ? routers[state.currentRouterIndex].childrens
        : routers;
      const LayoutComp = [
        {
          path: "/",
          component: await _import("/layout"),
          redirect: "/home",
          name: "主页",
          hidden: true,
          children: state.cachRouter,
        },
        {
          path: "/:pathMatch(.*)",
          redirect: "/404",
        },
      ];

      console.log(LayoutComp, "--LayoutComp--");

      state.addRouters = LayoutComp;
      state.routers = constantRouterMap.concat(LayoutComp);
    },
    SET_TOP_NAV_ACTIVE_KEY: (state, index) => {
      Session.set("MENU_ACTIVE_KEY", '');
      Session.set("TOP_NAV_ACTIVE_KEY", index);
      state.currentRouterIndex = index;
      state.currentRouter = state.asyncRouter[index].childrens;
    },
    SET_MENU_ACTIVE_KEY: (state, index) => {
      Session.set("MENU_ACTIVE_KEY", index);
      state.sidebarActiveIndex = index;
    },
  },
  getters: {
    addRouters(state) {
      return state.addRouters;
    },
  },
  actions: {
    GenerateRoutes({ commit }, roles) {
      console.log('11100', roles)
      return new Promise(async (resolve) => {
        const { data, code } = await getUserPermission();
        console.log('111', data)
        if (code === rescf.codeVal) {
          const GR = GetRoutes(data);
          const accessedRouters = GR.tree;
          permission.state.cachRouter = GR.route;
          commit("SET_ROUTERS", accessedRouters);
          resolve(accessedRouters);
        } else {
          resolve([]);
        }
      });
    },
    changeMenuActive({ commit }, index) {
      commit("SET_MENU_ACTIVE_KEY", index);
    },
    changeTopNavActive({ commit }, index) {
      if (Conf.HAS_TOP_NAV) {
        commit("SET_TOP_NAV_ACTIVE_KEY", index);
      }
    },
  },
};

export default permission;
